package com.stadium.web.controller;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fastsite.common.api.ApiException;
import com.fastsite.common.api.ApiResult;
import com.fastsite.common.api.ApiSecured;
import com.fastsite.common.api.ApiTokenUser;
import com.fastsite.common.domain.TokenUserObject;
import com.fastsite.common.enums.StatusEnum;
import com.fastsite.utils.validator.annotation.Money;
import com.stadium.web.domain.TokenUser;
import com.stadium.web.domain.User;
import com.stadium.web.domain.Venue;
import com.stadium.web.service.VenueService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Authorization;
import lombok.Data;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.persistence.Column;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


/**
 * 场馆对象 venue
 *
 * @author ruoyi
 * @date 2020-03-15
 */
@Api(tags = "场馆管理")
@Validated
@RestController
@RequestMapping("/web/venue")
public class VenueController {

    @Autowired
    private VenueService venueService;

    /**
     * 列表页面
     */
    @ApiSecured
    @ApiOperation(value = "场馆列表信息", authorizations = @Authorization(value = "token"))
    @ApiImplicitParams({
    @ApiImplicitParam(name="page",value="当前页数",required=false,paramType="form",dataType="Long"),
    @ApiImplicitParam(name="size",value="每页的数量",required=false,paramType="form",dataType="Long"),
//    @ApiImplicitParam(name="id",value="ID",required=false,paramType="form",dataType="Long"),
    @ApiImplicitParam(name="name",value="场馆名称",required=false,paramType="form",dataType="String"),
    @ApiImplicitParam(name="isReserve",value="是否预定 0:预定,1:未预定·",required=false,paramType="form",dataType="Long"),
    @ApiImplicitParam(name="regionId",value="所属区域",required=false,paramType="form",dataType="Long"),
//    @ApiImplicitParam(name="cost",value="场地费用",required=false,paramType="form",dataType="Double"),
//    @ApiImplicitParam(name="createdTime",value="创建时间",required=false,paramType="form",dataType="Date"),
//    @ApiImplicitParam(name="updatedTime",value="更新时间",required=false,paramType="form",dataType="Date"),
    })
    @GetMapping("/list")
    public ApiResult index(@ApiTokenUser TokenUser user,@ApiIgnore Venue venue){

        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching();
        matcher = matcher.withMatcher("name",match->match.contains());
        venue.setStatus(StatusEnum.OK.getCode());
        // 获取场馆列表
        Example<Venue> example = Example.of(venue, matcher);
        Page<Venue> list = venueService.getPageList(example);

        HashMap<String,Object> result = new HashMap<>();
        result.put("list", list.getContent());
        result.put("page", list);
        // 封装数据
        return ApiResult.ok(result,"获取场馆列表信息");
    }

    /**
     * 跳转到编辑页面
     */
    @ApiOperation("单个场馆信息")
    @GetMapping("/getOneVenue")
    public ApiResult getOneVenue(@RequestParam("id") Long id){
        Venue venue=  venueService.getById(id);
        return ApiResult.ok(venue,"获取单个场馆");
    }

    /**
     * 跳转到编辑页面
     */
    @ApiSecured
    @ApiOperation(value = "获取用户场馆列表信息", authorizations = @Authorization(value = "token"))
    @ApiImplicitParams({
            @ApiImplicitParam(name="page",value="当前页数",required=false,paramType="form",dataType="Long"),
            @ApiImplicitParam(name="size",value="每页的数量",required=false,paramType="form",dataType="Long"),
//    @ApiImplicitParam(name="id",value="ID",required=false,paramType="form",dataType="Long"),
            @ApiImplicitParam(name="name",value="场馆名称",required=false,paramType="form",dataType="String"),
            @ApiImplicitParam(name="isReserve",value="是否预定 0:预定,1:未预定·",required=false,paramType="form",dataType="Long"),
            @ApiImplicitParam(name="regionId",value="所属区域",required=false,paramType="form",dataType="Long"),
//    @ApiImplicitParam(name="cost",value="场地费用",required=false,paramType="form",dataType="Double"),
//    @ApiImplicitParam(name="createdTime",value="创建时间",required=false,paramType="form",dataType="Date"),
//    @ApiImplicitParam(name="updatedTime",value="更新时间",required=false,paramType="form",dataType="Date"),
    })
    @GetMapping("/userVenue")
    public ApiResult userVenue(@ApiTokenUser TokenUser user,@ApiIgnore Venue venue){

        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching();
        matcher = matcher.withMatcher("name",match->match.contains());
        venue.setUserId(user.getId());
        venue.setStatus(StatusEnum.OK.getCode());
        // 获取场馆列表
        Example<Venue> example = Example.of(venue, matcher);
        Page<Venue> list = venueService.getPageList(example);

        HashMap<String,Object> result = new HashMap<>();
        result.put("list", list.getContent());
        result.put("page", list);
        // 封装数据
        return ApiResult.ok(result,"获取场馆列表信息");
    }
    /**
     * 保存添加/修改的数据
     * @param venueFrom 实体对象
     */
    @ApiSecured
    @ApiOperation(value = "保存/修改单个场馆", authorizations = @Authorization(value = "token"), produces =  MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiImplicitParams({
//    @ApiImplicitParam(name="id",value="ID",required=false,paramType="body",dataType="Long"),
//    @ApiImplicitParam(name="name",value="场馆名称",required=false,paramType="body",dataType="String"),
//    @ApiImplicitParam(name="isReserve",value="是否预定 0:预定,1:未预定·",required=false,paramType="body",dataType="Long"),
//    @ApiImplicitParam(name="regionId",value="所属区域",required=false,paramType="body",dataType="Long"),
//    @ApiImplicitParam(name="cost",value="场地费用",required=false,paramType="body",dataType="Double"),
//    @ApiImplicitParam(name="createdTime",value="创建时间",required=false,paramType="body",dataType="Date"),
//    @ApiImplicitParam(name="updatedTime",value="更新时间",required=false,paramType="body",dataType="Date"),
//    })
    @PostMapping({"/save","/update"})
    @ResponseBody
    public ApiResult save(@ApiIgnore @ApiTokenUser TokenUserObject<User> user, @Valid @RequestBody VenueForm venueFrom){
        Venue venue = null;
        if(venueFrom.getCost().compareTo(new BigDecimal("0"))<0){
            throw new ApiException("费用不能小于0");
        }
        if(!StringUtils.isEmpty(venueFrom.getId())){
            //修改
            venue = venueService.getById(venueFrom.getId());
            if(!user.getId().equals(venue.getUserId())){
                return ApiResult.err("对不起，您没有该场馆得操作权限");
            }
            venue.setName(venueFrom.getName());
            venue.setRegionId(venueFrom.getRegionId());
            venue.setCost(venueFrom.getCost());
            venue.setLogo(venueFrom.getLogo());
            venue.setFromTime(venueFrom.getFromTime());
            venue.setToTime(venueFrom.getToTime());
        }else{
            //新增
            venue = new Venue();
            venue.setStatus(StatusEnum.OK.getCode());
            BeanUtils.copyProperties(venueFrom,venue);
            venue.setUserId(user.getId());
            venue.setCreatedTime(new Date());
            venue.setIsReserve(false);
        }
        // 保存数据
        venueService.save(venue);
        return ApiResult.ok("保存成功");
    }


    /**
     * 设置一条或者多条数据的状态
     */

    @ApiOperation(value = "修改场馆状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name="param",value="状态（1:正常，2:冻结,3:删除）",required=true,paramType="path",dataType="String"),
            @ApiImplicitParam(name="ids",value="修改[id]",required=true,paramType="form",dataType="List")}
    )
    @RequestMapping(value = "/status/{param}",method={RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public ApiResult status(
            @PathVariable("param") String param,
            @RequestParam(value = "ids", required = false) List<Long> ids){
        // 更新状态
        StatusEnum statusEnum = StatusEnum.getByCode(Byte.parseByte(param));
        if (venueService.updateStatus(statusEnum, ids)) {
            return ApiResult.ok(statusEnum.getMessage() + "成功");
        } else {
            return ApiResult.err(statusEnum.getMessage() + "失败，请重新操作");
        }
    }
}

@Data
@ApiModel("场馆保存form")
class VenueForm{
    /** ID */
    @ApiModelProperty("ID")
    private Long id;

    @ApiModelProperty("场馆logo")
    private String logo;

    /** 场馆名称 */
    @ApiModelProperty(value = "场馆名称",required = true)
    @NotBlank(message = "场馆名称不能为空")
    private String name;

    /** 所属区域 */
    @NotNull(message = "所属区域不能为空")
    @ApiModelProperty(value = "所属区域",required = true)
    private Long regionId;

    @NotBlank(message = "结束营业不能为空")
    @JsonFormat(pattern="HH:mm")
    @ApiModelProperty("结束营业时间")
    private String toTime;

    @NotBlank(message = "开始营业时间不能为空")
    @JsonFormat(pattern="HH:mm")
    @ApiModelProperty("开始营业时间")
    private String fromTime;

    /** 场地费用 */
    @NotNull(message = "场地费用不能为空")
    @ApiModelProperty(value = "场地费用",required = true)
    private BigDecimal cost;
}